﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Alfa.Common.ValueConverters {
	/// <summary>
	/// Value converter that translates <see cref="TimeSpan"/> to string.
	/// </summary>
	public sealed class TimeSpanToStringConverter : IValueConverter {
		/// <summary>
		/// Converts <see cref="TimeSpan"/> value to string.
		/// </summary>
		/// <param name="value">Value to convert. Should be <see cref="TimeSpan"/>.</param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns>Converted value (String)</returns>
		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
			if (value is TimeSpan) {
				if (parameter != null && parameter is string)
					return ((TimeSpan)value).ToString((string)parameter);
				else
					return ((TimeSpan)value).ToString( );
			}
			return null;
		}

		/// <summary>
		/// Converts back string value to <see cref="TimeSpan"/>.
		/// </summary>
		/// <param name="value">Value to convert. Should be string.</param>
		/// <param name="targetType"></param>
		/// <param name="parameter"></param>
		/// <param name="culture"></param>
		/// <returns>Converted value (TimeSpan)</returns>
		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
			if (value is string) {
				TimeSpan result;
				if (TimeSpan.TryParse((string)value, out result))
					return result;
			}
			return default(TimeSpan);
		}
	}
}
